/**
 * 获取cookie中内容
 * @param {String} Key
 * @returns
 */
const getCookie = function (key) {
  if (key == 'token') {
    if ($.cookie(key)) {
      return $.cookie(key);
    } else if(getQueryObject(window.location.href, "ACCESSTOKEN")){
      let ACCESSTOKEN = getQueryObject(window.location.href, "ACCESSTOKEN");
      sessionStorage.setItem('ACCESSTOKEN',ACCESSTOKEN);
      return ACCESSTOKEN;
    } else if (sessionStorage.getItem('ACCESSTOKEN')) {
      return sessionStorage.getItem('ACCESSTOKEN');
    }
  }
  
  if (key == 'party' || key == 'town' || key == 'unit' || key == 'village' || key == 'user') {
    if (!$.cookie(key) && !sessionStorage.getItem(key)) {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(`/auth/getAllList?username=`)}`,
        type: "get",
        dataType: "json",
        async: false,
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        success: function (res) {
          if (res.code == 200) {
            try {
              sessionStorage.setItem('town',res.data.area.town? res.data.area.town:"''");
            } catch (error) {
              sessionStorage.setItem('town',"''");
            }
            try {
              sessionStorage.setItem('village',res.data.area.village?res.data.area.village:"''");
            } catch (error) {
              sessionStorage.setItem('village',"''");
            }
            sessionStorage.setItem('unit',res.data.unit ? res.data.unit: "''");
            sessionStorage.setItem('party',res.data.party ? res.data.party: "''");
            sessionStorage.setItem('user',res.data.username ? res.data.username: "''");
          }
        },
      });
      return sessionStorage.getItem(key);
    } else if (!$.cookie(key) && sessionStorage.getItem(key)) {
      return sessionStorage.getItem(key);
    }
  }

  return $.cookie(key);
};

/**
 * 保存cookie中内容
 * @param {String} Key
 * @returns
 */
const setCookie = function (key, value) {
  return $.cookie(key, value);
};

/**
 * 移除cookie中内容
 * @param {String} Key
 * @returns
 */
const removeCookie = function (key) {
  return $.removeCookie(key);
};

/**
 * 请求头配置
 * @param {enum} Type
 * @returns
 */
const requestHeaders = function (Type = "FORM") {
  let ContentType;
  switch (Type) {
    case "FORM":
      ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
      break;
    case "JSON":
      ContentType = "application/json;charset=UTF-8";
      break;
    case "XML":
      ContentType = "text/html;charset=UTF-8";
      break;
  }
  return {
    "Content-Type": ContentType,
    AccessToken: getCookie("token"),
  };
};

/**
 * 响应预处理
 * @param {XMLHttpRequest} XMLHttpRequest
 * @param {*} user 账号
 */
const requestPretreatment = function (XMLHttpRequest, user = false, callback) {
  if (XMLHttpRequest.status == 200) {
    //成功
    const token = XMLHttpRequest.getResponseHeader("ACCESSTOKEN");
    if (token) {
      //是否有Token
      setCookie("token", token);
      if (user) {
        //是否登录
        // submitSave({ Add: { base_system_login_log: [{ IP: getIpAddress() }] } }, (res) => {
        //   setCookie("user", user);
        //   window.parent.document.location.href = "./index.html";
        // })
        $.ajax({
          headers: requestHeaders('JSON'),
          url: `${mh}/generalBusiness/generalSaveByRequestBody`,
          method: "post",
          data: JSON.stringify({
            Data: { Add: { base_system_login_log: [{ IP: getIpAddress() }] } },
          }),
          complete: function () {
            //获取权限
            $.ajax({
              headers: requestHeaders(),
              url: `${mh}/requestForward/requestForward?RequestURL=${encodeURIComponent(`/auth/getAllList?username=`)}`,
              type: "GET",
              success: (res) => {
                if (res.code == 200) {
                  try {
                    setCookie("town", res.data.area.town? res.data.area.town:"''");
                  } catch (error) {
                    setCookie("town", "''");
                  }
                  try {
                    setCookie("village", res.data.area.village?res.data.area.village:"''");
                  } catch (error) {
                    setCookie("village", "''");
                  }
                  setCookie("unit", res.data.unit ? res.data.unit: "''");
                  setCookie("party", res.data.party ? res.data.party: "''");
                } else {
                  setCookie("town", "''");
                  setCookie("village", "''");
                  setCookie("unit", "''");
                  setCookie("party", "''");
                }
                setCookie("user", user);
                window.parent.document.location.href = "./index.html";
              },
              complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest);
              },
              dataType: "json",
            });
          },
        });
      }
    }
  } else if (XMLHttpRequest.status == 302) {
    //重定向
    const redirect = XMLHttpRequest.getResponseHeader("REDIRECT");
    if (redirect) {
      if (user) {
        callback ? callback("error") : null;
      } else {
        removeCookie("token");
        removeCookie("user");
        removeCookie("party");
        removeCookie("town");
        removeCookie("unit");
        removeCookie("village");
        sessionStorage.removeItem('ACCESSTOKEN');
        sessionStorage.removeItem('village');
        sessionStorage.removeItem('party');
        sessionStorage.removeItem('town');
        sessionStorage.removeItem('unit');
        sessionStorage.setItem("REDIRECT", "登录已过期，请重新登录！");
        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
      }
    }
  } else if (XMLHttpRequest.status == 500) {
    callback ? callback("error") : null;
  } else if (XMLHttpRequest.status == 404) {
    callback ? callback("error") : null;
  }
};
